import { getShops } from "@src/api/catering";
import router from "@src/router";
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from '@src/store/base';
import location from "@src/store/location";

Component({
  options: {
    addGlobalClass: true
  },
  behaviors: [router.routerBehavior, storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }, {
    store: location,
    fields: ['latitude', 'longitude', 'auth'],
    actions: ['getLocation', 'showAuthTip']
  }],
  data: {
    listData: [],
    isHasData: [],
    shopList: [], // 商店信息,
  },
  lifetimes: {
    attached: function () {
      // this.fetchData()
      if (this.data.latitude == null || this.data.longitude === null) {
        this.getLocation().then((res) => {
          this.queryShop(res.latitude, res.longitude)
          // this.queryNearbyShopListReq(res.latitude, res.longitude);
        }).catch(error => {
          this.showAuthTip(error);
          this.queryShop();
        });
      } else {
        this.queryShop()
      }
    },
    detached: function () {
    }
  },
  pageLifetimes: {},
  methods: {
    queryShop(latitude, longitude) {
      console.log('this.data.latitude', this.data.latitude);
      let data = {}
      if (latitude) {
        data.latitude = latitude
        data.longitude = longitude
      }
      console.log('data', data)
      getShops(data).then(res => {
        if (res.code === 0) {
          let data = res.data;
          data.forEach(item => {
            if (item.distance) {
              if (item.distance < 1000) {
                item.distance = item.distance + "米"
              } else {
                item.distance = (Math.round(item.distance / 100) / 10).toFixed(1) + "km"
              }
            }
          })
          this.setData({
            shopList: data
          })
        }
      })
    },
    handleProxy(e) {
      console.log('e', e);
      let shopId = e.currentTarget.dataset.item.shopId;
      router.push({ name: 'catering/index', params: { shopId: shopId } })
    }
  }
})
